// myPages/Reply/Reply.js
var md5 = require('../../utils/md5.js');
const util = require('../../utils/util.js');
const api = require('../../config/api.js');
const recorderManager = wx.getRecorderManager();
const innerAudioContext = wx.createInnerAudioContext();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    fastAskOrder: [],
    orderId: "",
    localImg: '', //图片数组
    netImg: '', //网络路径
    selectType: '',
    sayBtnTxt: '按住说话',
    sumBtnHide: false, //提交按钮  true隐藏 false显示
    sayBtnHide: true, //录音按钮  true隐藏 false显示
    isPlay: false, //音频是否播放
    isVoice: true, //录音后音频显示,
    localVoice: '', //音频数组
    netVoice: '', //音频网络路径
    voiceDuration: 0,
    imgUploadProgess: 0, //图片上传进度
    voiceUploadProgess: 0, //声音上传进度
    answerTxt: '', //提问的问题
    sayBtnBg:true,
  },

  //添加上传图片
  chooseImageTap: function() {
    var that = this;
    wx.showActionSheet({
      itemList: ['从相册中选择', '拍照'],
      itemColor: "#00000",
      success: function(res) {
        if (!res.cancel) {
          if (res.tapIndex == 0) {
            that.chooseWxImage('album')
          } else if (res.tapIndex == 1) {
            that.chooseWxImage('camera')
          }
        }
      }
    })
  },
  // 图片本地路径
  chooseWxImage: function(type) {
    var that = this;
    wx.chooseImage({
      sizeType: ['original', 'compressed'],
      sourceType: [type],
      success: function(res) {
        console.log('选择的图片本地地址' + res.tempFilePaths[0]);
        //调用上传方法
        that.setData({
          localImg: res.tempFilePaths[0]
        })
        that.upImgs(res.tempFilePaths[0])
      }
    })
  },
  //图片上传服务器
  upImgs: function(imgurl) {
    var that = this;
    const uploadTask = wx.uploadFile({
      url: api.UPLOAD_FILE,
      filePath: that.data.localImg,
      name: 'file',
      header: {
        'content-type': 'multipart/form-data'
      },
      success: function(res) {
        console.log('图片上传返回结果:' + res.data)
        var result = JSON.parse(res.data)
        console.log('图片上传' + result.message)
        that.setData({
          netImg: result.message
        })
      }
    })
    uploadTask.onProgressUpdate((res) => {
      if (res.progress == 100) {
        that.setData({
          imgUploadProgess: res.progress
        })
      }
    })
  },

  // 录音
  showSayBtn: function() {
    console.log(this.data.sumBtnHide);
    this.setData({
      sumBtnHide: !this.data.sumBtnHide,
      sayBtnHide: !this.data.sayBtnHide
    })
  },
  //获取用户输入的问题
  answerInput: function(e) {
    this.setData({
      answerTxt: e.detail.value
    })
  },
  //监听事件 按住说话
  //按住说话
  sayVideo: function(e) {
    var that = this;
    const options = {
      duration: 60000,
      sampleRate: 16000,
      numberOfChannels: 1,
      encodeBitRate: 96000,
      format: 'mp3',
      frameSize: 50
    };
    that.setData({
      sayBtnBg: false,
    })
    if (this.data.status != 2) {
      //没有授权
      wx.authorize({
        scope: 'scope.record',
        success() {
          console.log("录音授权成功");
          //第一次成功授权后 状态切换为2
          that.setData({
            status: 2,
          })
        },
        fail() {
          wx.openSetting({
            success: (res) => {
              console.log(res.authSetting);
              if (!res.authSetting['scope.record']) {
                //未设置录音授权
                console.log("未设置录音授权");
                wx.showModal({
                  title: '提示',
                  content: '您未授权录音，功能将无法使用',
                  showCancel: false,
                  success: function(res) {},
                });
              } else {
                //第二次才成功授权
                console.log("设置录音授权成功");
                that.setData({
                  status: 2,
                })
                recorderManager.start(options);
              }
            },
            fail: function() {
              console.log("授权设置录音失败");
            }
          })
        }

      });
    } else {
      recorderManager.start(options);
      that.setData({
        sayBtnTxt: '松开结束'
      })
    }
  },
  //松开
  sayVideoEnd: function(e) {
    var that = this;
    recorderManager.stop(); //先停止录音  
    recorderManager.onStop((res) => { //监听录音停止的事件
      if (res.duration < 1000) {
        wx.showToast({
          title: '录音时间太短',
          duration: 1000
        });
        that.setData({
          sayBtnTxt: '按住说话',
          sumBtnHide: !that.data.sumBtnHide,
          sayBtnHide: !that.data.sayBtnHide,
          isVoice: false,
          sayBtnBg:true,
        })
        return;
      } else {
        wx.showToast({
          title: '正在保存...',
        });
        that.setData({
          sayBtnTxt: '按住说话',
          sumBtnHide: !that.data.sumBtnHide,
          sayBtnHide: !that.data.sayBtnHide,
          isVoice: false,
          sayBtnBg: true,
        })
        var tempFilePath = res.tempFilePath; // 文件临时路径
        console.log('tempFilePath' + tempFilePath);
        var sec = parseInt(res.duration / 1000 % 60);
        if (sec.toString().length == 1) {
          sec = `0${sec}`;
        }
        console.log('sec' + sec);
        // var temp = tempFilePath.replace('.mp3', '') //转换格式 默认silk后缀
        that.setData({
          localVoice: tempFilePath,
          voiceDuration: sec
        })
        console.log('录音本地目录' + tempFilePath);
        that.voiceUpload(tempFilePath)
      }
    });
  },
  // 音频上传服务器
  voiceUpload: function(localVoice) {
    var that = this;
    wx.showLoading({
      title: '正在提交...',
    });
    var voiceUpload = wx.uploadFile({
      url: api.UPLOAD_FILE, //上传服务器的地址
      filePath: localVoice, //临时路径
      name: 'file',
      header: {
        'content-type': 'multipart/form-data'
      },
      success: function(res) {
        console.log('音频上传' + res.data)
        var result = JSON.parse(res.data)
        console.log('音频上传' + result.message)
        that.setData({
          netVoice: result.message
        })
        wx.hideLoading();
      },
      fail: function(err) {
        wx.hideLoading();
        console.log(err.errMsg); //上传失败
      }
    });
    voiceUpload.onProgressUpdate((res) => {
      if (res.progress == 100) {
        that.setData({
          voiceUploadProgess: res.progress
        })
      }
    })
  },
  //播放 或是暂停语音
  playAudio: function(e) {
    // 因全局已经 注册过上下文 直接用innerAudioContext就可以
    // 在wxml中 需要传 data-item="{{item}}"  循环出来的当前信息
    let item = e.currentTarget.dataset.item;
    let that = this;
    //音频地址
    // innerAudioContext.src = item.AudioSrc;
    innerAudioContext.src = that.data.localVoice;

    // innerAudioContext.src = '//music.163.com/outchain/player?type=2&id=1374056687&auto=1&height=66';
    //在ios下静音时播放没有声音，默认为true，改为false就好了。
    innerAudioContext.obeyMuteSwitch = false;
    if (that.data.isPlay === false) {
      //点击播放
      innerAudioContext.play();
      that.setData({
        isPlay: true
      })
    } else {
      //点击暂停
      innerAudioContext.stop();
      that.setData({
        isPlay: false
      })
    };
    // //播放结束
    innerAudioContext.onEnded(() => {
      innerAudioContext.stop();
    });
  },
  // 提交回答
  answerQ: function() {
    var that = this
    var localImg = that.data.localImg
    var localVoice = that.data.localVoice

    if (!localImg && !localVoice && !that.data.answerTxt){
      wx.showToast({
        title: '请回答问题再提交',
        icon: 'none'
      });
      return
    }

    if (localVoice && that.data.voiceUploadProgess != 100) {
      wx.showToast({
        title: '录音正在上传,请稍后提交',
        icon: 'none'
      });
      return
    }

    if (localImg && that.data.imgUploadProgess != 100) {
      wx.showToast({
        title: '图片正在上传,请稍后提交',
        icon: 'none'
      });
      return
    }

    let fastAskOrderUpdate = {
      id: that.data.fastAskOrder.id,
      status: 2,
      answer: that.data.answerTxt,
      voice: that.data.netVoice,
      picture: that.data.netImg
    }
    that.updateOrder(fastAskOrderUpdate)
  },

  updateOrder(fastAskOrder){
    util.request(api.FastAskOrderUpdate, fastAskOrder, 'POST', true).then(function (res) {
      if (res.code === 200) {
        wx.navigateTo({
          url: '../../myPages/techerReLists/techerReLists'
        })
      } else {
        wx.showToast({
          title: res.message,
          icon: 'none'
        });
      }
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this
    var fastAskOrderId = options.fastAskOrderId
    util.request(api.SelectFastAskOrderById, {
      fastAskOrderId: fastAskOrderId, //订单id
    }, 'GET').then(function(res) {
      if (res.code == 200) {
        that.setData({
          fastAskOrder: res.result,
          orderId: res.result.id != undefined ? md5.b64Md5(res.result.id) : "",
        })
      }
    });
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    this.innerAudioContext.stop();
    this.innerAudioContext.destroy();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
})